package com.test.webmanage.filter;

import com.alibaba.fastjson.JSON;
import com.test.webmanage.pojo.Result;
import com.test.webmanage.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebFilter
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String url= req.getRequestURI();
        if(url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String jwt = req.getHeader("token");
        if(jwt==null|| jwt.isEmpty()){
           Result result = Result.error("NOT_LOGIN");
           String notlogin = JSON.toJSONString(result);
           resp.getWriter().write(notlogin);
           return;
        }
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e)
            {
                Result result = Result.error("NOT_LOGIN");
                String notlogin = JSON.toJSONString(result);
                resp.getWriter().write(notlogin);
                return;
            }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
